package com.xp.record25.bio.nio.writeable;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;

public class NioServerDemo {

    public static void main(String[] args) throws IOException {
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        ssc.bind(new InetSocketAddress(8888));
        Selector selector = Selector.open();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        //这里注册了感兴趣的事件，以及确认了附件
        SelectionKey selectionKey = ssc.register(selector,0);
        selectionKey.interestOps(SelectionKey.OP_ACCEPT);
        while (true){
            selector.select();
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                //这一步一定要写，不然就会无限循环
                iterator.remove();
                if (key.isAcceptable()) {
                    //这里可以直接获取channel 可以直接使用 ServerSocketChannel 因为只有这个channel绑定这个 SelectionKey
                    ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                    //建立连接，获取客户端连接
                    SocketChannel sc = channel.accept();
                    StringBuilder builder = new StringBuilder();
                    for (long i = 0L; i < 88000000L; i++) {
                        builder.append("a");
                    }
                    ByteBuffer buf = StandardCharsets.UTF_8.encode(builder.toString());
                    int r = sc.write(buf);
                    System.out.println(r);
                    while (buf.hasRemaining()) {
                        int write = sc.write(buf);
                        key.interestOps(key.interestOps() & ~SelectionKey.OP_WRITE);
                        key.attach(buf);
                        System.out.println(write);
                    }
                }else if (key.isWritable()) {
                    SocketChannel channel = (SocketChannel) key.channel();
                    System.out.println("--------------------------------isWritable");
                    ByteBuffer buffer1 = (ByteBuffer) key.attachment();
                    int write = channel.write(buffer1);
                    System.out.println(write);
                    if (!buffer1.hasRemaining()) {
                        key.attach(null);
                        key.interestOps(key.interestOps() - SelectionKey.OP_WRITE);
                    }
                }
            }
        }

    }


    static class Worker implements Runnable {

        private Thread thread;
        private Selector selector;



        @Override
        public void run() {

        }
    }

}
